import redis
import json
from datetime import datetime, timedelta

class RedisManager:
    """Redis管理器"""
    
    def __init__(self, host='localhost', port=6379, db=0, password=None):
        """
        初始化Redis连接
        
        Args:
            host (str): Redis主机地址
            port (int): Redis端口
            db (int): Redis数据库编号
            password (str): Redis密码
        """
        try:
            self.redis_client = redis.Redis(
                host=host,
                port=port,
                db=db,
                password=password,
                decode_responses=True
            )
            # 测试连接
            self.redis_client.ping()
            print("Redis连接成功")
        except Exception as e:
            print(f"Redis连接失败: {e}")
            self.redis_client = None
    
    def add_token_to_blacklist(self, token, expire_time=None):
        """
        将token添加到黑名单
        
        Args:
            token (str): JWT token
            expire_time (int): 过期时间（秒），如果为None则使用token本身的过期时间
        """
        if not self.redis_client:
            return False
        
        try:
            # 黑名单key格式: blacklist:token
            key = f"blacklist:{token}"
            
            if expire_time is None:
                # 默认1小时过期
                expire_time = 3600
            
            # 设置token为黑名单，并设置过期时间
            self.redis_client.setex(key, expire_time, "blacklisted")
            return True
        except Exception as e:
            print(f"添加token到黑名单失败: {e}")
            return False
    
    def is_token_blacklisted(self, token):
        """
        检查token是否在黑名单中
        
        Args:
            token (str): JWT token
            
        Returns:
            bool: True表示在黑名单中，False表示不在
        """
        if not self.redis_client:
            return False
        
        try:
            key = f"blacklist:{token}"
            result = self.redis_client.get(key)
            return result is not None
        except Exception as e:
            print(f"检查token黑名单失败: {e}")
            return False
    
    def remove_token_from_blacklist(self, token):
        """
        从黑名单中移除token
        
        Args:
            token (str): JWT token
        """
        if not self.redis_client:
            return False
        
        try:
            key = f"blacklist:{token}"
            self.redis_client.delete(key)
            return True
        except Exception as e:
            print(f"从黑名单移除token失败: {e}")
            return False
    
    def store_refresh_token(self, user_id, refresh_token, expire_time=3600):
        """
        存储刷新token
        
        Args:
            user_id (int): 用户ID
            refresh_token (str): 刷新token
            expire_time (int): 过期时间（秒）
        """
        if not self.redis_client:
            return False
        
        try:
            key = f"refresh_token:{user_id}"
            self.redis_client.setex(key, expire_time, refresh_token)
            return True
        except Exception as e:
            print(f"存储刷新token失败: {e}")
            return False
    
    def get_refresh_token(self, user_id):
        """
        获取用户的刷新token
        
        Args:
            user_id (int): 用户ID
            
        Returns:
            str: 刷新token，如果不存在返回None
        """
        if not self.redis_client:
            return None
        
        try:
            key = f"refresh_token:{user_id}"
            return self.redis_client.get(key)
        except Exception as e:
            print(f"获取刷新token失败: {e}")
            return None
    
    def delete_refresh_token(self, user_id):
        """
        删除用户的刷新token
        
        Args:
            user_id (int): 用户ID
        """
        if not self.redis_client:
            return False
        
        try:
            key = f"refresh_token:{user_id}"
            self.redis_client.delete(key)
            return True
        except Exception as e:
            print(f"删除刷新token失败: {e}")
            return False

# 创建全局Redis实例
redis_manager = RedisManager()
